import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  method: '',
  async: '',
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['Content-Type'] = 'application/json'
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    // console.log('原method:' + config.method)
    config.method = config.method || 'post' // 默认post方式
    // console.log('新method:' + config.method)
    // console.log('原asycn:' + config.async)
    if (config.async === '') {
      config.async = true // 同步异步
    }
    // console.log('新async:' + config.async)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // console.log('返回状态' + response.status)
    if (response.status === 500) {
      return Promise.reject(new Error('服务异常，请稍后重试！'))
    }
    const res = response.data
    // console.log(res)
    // if the custom code is not 20000, it is judged as an error.
    if (res.returnCode !== '00200') {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    if (error && error.stack.indexOf('timeout') > -1) {
      Message({
        message: '请求超时，请重试！',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('请求超时，请重试！')
    }
    // console.log('返回值：' + error.response.status)
    if (error.response.status === 401 && error.response.data.returnCode === '00601') {
      MessageBox.alert('登录信息失效，请重新登录', {}).then(() => {
        location.reload()
      })
    } else {
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      const message = (error.response && error.response.data && error.response.data.msg) || '请求失败，请稍后重试'
      return Promise.reject(message)
    }
  })
export default service
